package com.example.ribbonconsumer.command;

import org.springframework.web.client.RestTemplate;

import com.example.ribbonconsumer.model.Book;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;

public class BookCommand extends HystrixCommand<Book>{
	
	private RestTemplate restTemplate;
	
	private String name;

	public BookCommand(RestTemplate restTemplate,String name) {
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BookGroup"))
				.andCommandKey(HystrixCommandKey.Factory.asKey("BookCommand"))
				.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("ThreadPoolKey")));
		this.restTemplate = restTemplate;
		this.name = name;
	}
	
	@Override
	protected Book run(){
		return restTemplate.getForEntity("http://HELLO-SERVICE/getbookbyname?name={1}", Book.class, name).getBody();
	}
	
	@Override
	protected Book getFallback(){
		return new Book();
	}
	
	@Override
	protected String getCacheKey(){
		return name;
	}
	
	public static void flushCache(String name){
		HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("BookCommand"), HystrixConcurrencyStrategyDefault.getInstance())
		.clear(name);
	}

}
